<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\User as Staff;
use Illuminate\Http\Request;

class StaffController extends Controller
{

//    use \App\Traits\OperationLog;
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '员工管理';


    protected $market;


    /**
     * @param Request $req
     * @param $status int 状态 1-在职, 2-离职
     * @return array
     */
    public function index(Request $req)
    {
        $all = $req->all();
        $qry = Staff::query();
        $per_page = $this->getPerPage($req);

        if (isset($all['name'])) {
            $qry->where('name', $all['name']);
        }
        if (isset($all['no'])) {
            $qry->where('no', $all['no']);
        }
        if (isset($all['status'])) {
            $qry->where('status', $all['status']);
        }
        $list = $qry->paginate($per_page);
        return $this->resSuccess('', $list);


    }

    // 新增
    public function store(Request $req)
    {
        $all = $req->all();

        $no = isset($all['no']) ? trim($all['no']) : '';
        if (!$no || !isset($all['name']) ) {
            return $this->resError('用户信息不全');
        }
        $user = Staff::where('no', $no)->first();
        if ($user) {
            return $this->resError('员工号 “'.$no.'”，已存在！');
        }
        $all['creator'] = $req->user()->id;
        $user = new Staff($all);

        if ($user->save()) {
            return $this->resSuccess();

        }
        return $this->resError();

    }

    // 编辑
    public function update($id, Request $req)
    {
        $all = $req->all();
        $no = isset($all['no']) ? trim($all['no']) : '';
        if (!$no || !isset($all['name']) ) {
            return $this->resError('用户信息不全');
        }
        $user = Staff::find($id);
        if (!$user) {
            return $this->resError('员工信息有误！');
        }

        $repeat = Staff::where('no', $no)->where('id', '!=', $id)->first();
        if ($repeat) {
            return $this->resError('员工号 “'.$no.'”，已存在！');
        }
        $user->fill($all);
        if ($user->save()) {
            return $this->resSuccess();
        }
        return $this->resError();
    }


    public function export(Request $req)
    {
        $req->offsetSet('page', 1);
        $req->offsetSet('per_page', 9999);
        $res = $this->index($req);

        $data[] = [
            '工号',
            '姓名',
            '部门',
            '职级',
            '邮箱',
            '电话',
            '状态',
            '创建时间',
            '更新时间',
            '创建人',
        ];
        if (isset($res['dat']) && count($res['dat']->items())>0) {
            foreach ($res['dat']->items() as $v) {
                $data[] = [
                    $v['no'],
                    $v['name'],
                    @$v->department->name,
                    @Staff::JobClass[$v['class_id']],
                    $v['email'],
                    $v['phone'],
                    @Staff::Status[$v['status']],
                    $v['created_at'],
                    $v['updated_at'],
                    $v['creator'],
                ];
            }
        }
//        return $data;
        return $this->resExcel($data, $this->title.'.xlsx');
    }

    // 批量新增(导入)员工  (方法名不要使用import)
    public function importStaff(Request $req)
    {
        $header = [
            'name',
            'no', // 工号
            'dept_id', // 部门id
            'class_id',
            'email',
            'phone',
            'status',
        ];
        # 解析Excel
        $eData = $this->reqExcel($req->file('file'), $header);

        $data = [];
        $staff = [];
        // 循环每一行
        foreach ($eData as $i=> $row) {
            $no = trim($row['no']);
            if (isset($staff[$no])) {
                return $this->resError('第'.($i+2).'行数据"工号" 重复！');
            }
            $name = trim($row['name']);
            if (!$no && !$name) continue;

            if (!$no || !$name || !$row['class_id'] || !$row['dept_id'] || !$row['status'] || !$row['phone'] ||
                !$row['email']) {
                return $this->resError('第'.($i+2).'行数据填写不完整！');
            }

            $exist = Staff::where('no', $no)->first();
            if ($exist) {
                return $this->resError('工号( '.$no.' )已经存在！');
            }

            $class = Staff::getJobClassId($row['class_id']);
            if (!$class) {
                return $this->resError('第'.($i+2).'行"职级"填写错误！');
            }

            $status = Staff::getStatusId($row['status']);
            if (!$status) {
                return $this->resError('第'.($i+2).'行"状态"填写错误！');
            }

            $dept = Department::where('name', trim($row['dept_id']))->first();
            if (!$dept) {
                return $this->resError('第'.($i+2).'行"部门"填写错误！');
            }

            $row['class_id'] = $class;
            $row['status'] = $status;
            $row['dept_id'] = $dept->dept_id;
//            $row['creator'] = $req->user()->id;

            $data[] = $row;
            $staff[$no] = $no;
        }
        collect($data)->chunk(999)->each(function($gp) {
            Staff::insert($gp->all());
        });
        return $this->resSuccess();
    }


    /**
     * 导入模板
     * @param Request $req
     */
    public function importTpl(Request $req)
    {
        $url = $this->downFile('staff.xlsx');
        return $this->resSuccess('', [
            'url'=> $url,
            'target' => '_blank',
        ]);
    }




    /**
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Staff());

        $grid->model()->notAdmin();

        $grid->filter(function ($filter) {
            // $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1/5, function($filter){
                $filter->equal('name','姓名');
            });

            $filter->column(1/5, function($filter){
                $filter->equal('no','工号');
            });
            $filter->column(1/5, function($filter){
                $filter->in('dept_id','部门')->multipleSelect(Department::selectOptions(null, '请选择'));
            });

            $filter->column(1/5, function($filter){
                $filter->equal('class_id','职级')->select(Staff::JobClass);
            });
            $filter->column(1/5, function($filter){
                $filter->equal('status','状态')->select(Staff::Status);
            });

        });
        $grid->column('id','No.');
        $grid->column('no','工号');
        $grid->column('name','姓名');
        $grid->column('dept_id','部门')->replace(Department::getAllDept());
        $grid->column('class_id','职级')->replace(Staff::JobClass);
        $grid->column('email','邮箱');
        $grid->column('phone','电话');
        $grid->column('status','状态')->replace(Staff::Status);
        $grid->column('created_at','创建时间');
        $grid->column('creator','创建人')->replace(AdminUser::getAdminUserByShortNameCache());
        $grid->column('updated_at','更新时间');

        $this->disableButton(['view']);
        $this->disableButtonWhere('delete', function ($actions)  {
            return $actions->row->is_use;
        });

        $this->toolsButton( new ImportStaffAction());

        return $grid;
    }




    protected function form(): Form
    {
        $form = new Form(new Staff());

        if($form->isEditing()){
            $id = request()->route()->parameters();
            $form->text('no', '工号')->updateRules(['required', "unique:yt_new_users,no,{$id['staff']}"], ['unique' => '系统已存在该工号，请检查。'])
            ->required();
        }else{
            $form->text('no', '工号')->creationRules(['required', "unique:yt_new_users,no"], ['unique' => '系统已存在该工号，请检查。'])
            ->required();
        }

        // $form->text('en_name', '姓名')->creationRules(['required', "unique:yt_staff,en_name"], ['unique' => '姓名已存在']);
        $form->text('name', '姓名')->required();
        $form->select('dept_id','部门')->options(function() {
            return  Department::selectOptions(null,'请选择部门');
        })->required()->rules('required');

        $form->email('email','邮箱')->required();
        $form->select('status','状态')->options(function() {
            return Staff::Status;
        })->required();

        $form->select('class_id','职级')->options(function() {
            return Staff::JobClass;
        })->required();

        $form->text('phone','电话')->required();
        if($form->isCreating()){
            $form->hidden('creator')->default(Admin::user()->id);
        }


        $form->saving(function (Form $form) {
            // 操作日志
            self::setOrigin($form);
        });

        $form->saved(function (Form $form)  {
            $model = $form->model();
            self::saveLog($form, 'no', $model->id);
//            Cache::forget('adminUserEmail');

            // 重置数据权限缓存
            putLogUserCategory($model->id);
            putLogUserWarehouse($model->id);
            putLogUserSaleAccount($model->id);

        });



        return $form;
    }


}
